var selectedDataRow = '', selectedOrgRow = '';
var isInit = true, isLeftInit = true;
var isInitCheck = true;
var s_operType = 'revoke';
var vueObj = new Vue({
    el: "#vue",
    data: {
        teamObj: searchInfo
    }
});

$(function () {
    newCheck.initByName('_reason');
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedDataRow = row;
            openInfoOrgTeamPage();
        },
    }
    regValidate(["#_teamForm","#note"]);
    initTextSearch("#docName",
        basePath + 'bizOrgTeam/getDocData?t='+new Date().getTime()+'&docName=',
        ['docCode', 'docName'],
        {'docCode':'医生编码', 'docName':'医生姓名'},
        'docCode',
        'docName',
        true,
        selectDocValue,
        noSelectDocValue,
        false);
    initLaydate();

    initScanQrCodePage('minApp', 'publish', doCommitTeam,closeScanOrCodePage,refreshQrCode);
});

function initLaydate() {
    laydate.render({
        elem: '#timeInterval'
        ,type: 'date'
        ,range: true //或 range: '~' 来自定义分割字符
        // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", preDate) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", curDate)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
}

function doOrgRefresh() {
    selectedOrgRow = '';
    $('#orgTable').bootstrapTable('refresh', {
        url: basePath + 'bizOrgTeam/pageFindOrgData?t=' + new Date().getTime(),
    });
}

function selectDocValue(data) {
    if (!data || !data.docCode) {
        return;
    }
    $('#docCode').val(data.docCode);
}

function noSelectDocValue() {
    $('#docCode').val('');
}

$('#setReasonPage').on('hidden.bs.modal', function () {
    // 执行一些动作...
    $("input[type=checkbox][name=_reason]").removeAttr("checked");
    $('#reason').val('');
});

$('#scanQrCodePage').on('hidden.bs.modal', function () {
    // 执行一些动作...
    $('#scanCode').val('');
    $('#_validNum').val('');
});

function getOrgParams(params) {
    var pageSize = params.pageSize;
    var pageNo = params.pageNumber;
    if (isLeftInit) {
        isLeftInit = false;
        pageSize = searchInfo.orgPageSize ? searchInfo.orgPageSize : params.pageSize;
        pageNo = searchInfo.orgPageNo ? searchInfo.orgPageNo : params.pageNumber;
    }
    var postData={
        pageSize : pageSize,
        pageNo : pageNo
    };
    postData.orgName = $.trim($("#orgName").val());
    return postData;
}
//右边选中事件
$("#orgTable").on("click-row.bs.table",function(e,row,ele){
    $("#orgTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedOrgRow = row;
    doRefresh();
});


function doRefresh() {
    selectedDataRow = '';
    var teamName = $('#teamName').val();
    var docCode = $('#docCode').val();
    var dataStatus = $('#dataStatus').val();
    var status = $('#status').val();
    var timeInterval = $('#timeInterval').val();
    var beginTime = '';
    var endTime = '';
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            beginTime = dates[0];
            endTime = dates[1];
        }
    }
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'bizOrgTeam/pageFindBizOrgTeam?t=' + new Date().getTime(),
        query: {
            teamName : teamName,
            docCode : docCode,
            dataStatus : dataStatus,
            status : status,
            beginTime : beginTime,
            endTime : endTime,
            orgCode : selectedOrgRow ? selectedOrgRow.orgCode : '',
        }
    });
}
function getParams(params) {
    var pageNumber = params.pageNumber;
    var pageSize = params.pageSize;
    var orgCode = selectedOrgRow ? selectedOrgRow.orgCode : '';
    if (isInit) {
        isInit = false;
        pageSize = searchInfo.pageSize ? searchInfo.pageSize : params.pageSize;
        pageNumber = searchInfo.pageNo ? searchInfo.pageNo : params.pageNumber;
        orgCode = searchInfo.orgCode;
    }
    var teamName = $('#teamName').val();
    var docCode = $('#docCode').val();
    var dataStatus = $('#dataStatus').val();
    var status = $('#status').val();
    var timeInterval = $('#timeInterval').val();
    var beginTime = '';
    var endTime = '';
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            beginTime = dates[0];
            endTime = dates[1];
        }
    }
    var postData = {
        teamName : teamName,
        docCode : docCode,
        dataStatus : dataStatus,
        status : status,
        beginTime : beginTime,
        endTime : endTime,
        orgCode : orgCode,
        pageSize : pageSize,
        pageNo : pageNumber
    };
    return postData;
}

//左边选中事件
$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedDataRow = row;
    changeStatueBtn(row.status == 'available',"冻结","恢复");
});

var VueObj = new Vue({
    el:"#addPage",
    data:{obj:{}}
});
var beforeList = [],afterList = [];
function add(type) {
    beforeList = new Array();
    afterList = new Array();
    $('.note_lable').remove();
    resetFormTip("#_teamForm");
    resetInputCss("#_teamForm");
    if(type == 'add'){
        if (selectedOrgRow =='') {
            toastr.error(common_no_choose_msg.format("操作"));
            return;
        }
        var obj= {title:"新增机构团队",orgName:selectedOrgRow.orgName};
        VueObj.$set(VueObj.$data,"obj",JSON.parse(JSON.stringify(obj)));
        $("#addPage").modal(true);
    }else{
        if (selectedDataRow =='') {
            toastr.error(common_no_choose_msg.format("操作"));
            return;
        }
        if(selectedDataRow.bizEnumList != null && selectedDataRow.bizEnumList.length > 0 ){
            var str = "";
            for(var index in selectedDataRow.bizEnumList){
                beforeList.push(selectedDataRow.bizEnumList[index].enumCode);
                str +="  <div class=\"note_lable\" name=\"role\" value=\"" +selectedDataRow.bizEnumList[index].enumName +"\"  cname='" +
                    selectedDataRow.bizEnumList[index].enumCode+"'>\n" +
                    "                                    <lable>" + selectedDataRow.bizEnumList[index].enumName+"</lable>\n" +
                    "                                    <div  onclick=\"$(this).parent().remove()\">X</div>\n" +
                    "                                    <div  class=\"note_mind\"></div>\n" +
                    "                                </div>"
            }
            $('.note').append(str);
        }
        var obj= selectedDataRow;
        obj.title = "编辑机构团队";
        obj.orgName = selectedOrgRow.orgName;
        VueObj.$set(VueObj.$data,"obj",JSON.parse(JSON.stringify(obj)));
        $("#addPage").modal(true);
    }
}

function openAddOrgTeamPage() {
    if (!selectedOrgRow || selectedOrgRow =='') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    doEditEvent('add', selectedOrgRow.orgCode, selectedOrgRow.isvPid, selectedOrgRow.orgName, 0);
}

function openEditOrgTeamPage() {
    if (!selectedDataRow ||  selectedDataRow=='') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error('待审核数据无法编辑');
        return;
    }
    doEditEvent('edit', selectedDataRow.orgCode, selectedDataRow.isvPid, selectedOrgRow.orgName, selectedDataRow.id);
}

function openInfoOrgTeamPage() {
    if (!selectedDataRow ||  selectedDataRow=='') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    doEditEvent('info', selectedDataRow.orgCode, selectedDataRow.isvPid, selectedOrgRow.orgName, selectedDataRow.id);
}

function doEditEvent(command, orgCode, isvPid, orgName, orgTeamId) {
    var searchOrgName = $('#orgName').val();
    var tableOptions1 = $('#orgTable').bootstrapTable('getOptions', null);
    var tableOptions2 = $('#dataTable').bootstrapTable('getOptions', null);

    window.location.href = basePath + 'bizApp/editOrgTeamPage?editType=' + command +
        '&t=' + new Date().getTime() +
        '&isOrgExist=' + searchInfo.isOrgExist +
        '&isDocExist=' + searchInfo.isDocExist +
        '&' + $('#searchForm').serialize() +
        '&orgPageNo=' + tableOptions1.pageNumber +
        '&orgPageSize=' + tableOptions1.pageSize +
        '&pageNo=' + tableOptions2.pageNumber +
        '&pageSize=' + tableOptions2.pageSize +
        '&orgCode=' + orgCode +
        '&isvPid=' + isvPid +
        '&id=' + orgTeamId +
        '&orgName=' + orgName +
        '&searchKey=' + searchOrgName;
}

function dosave() {



    // getTeamRef


    if(!$("#_teamForm").valid()) return;
    var postData = {};
    $("#_teamForm").serializeArray().map((function (item,index,input) {
        postData[item.name] = item.value;
    }));
     var list = new Array();
    $(".note_lable[name=role]").each(function (index,value) {
        if ($(value).attr('cname')){
            afterList.push($(value).attr('cname'));
        }else{
            list.push({enumName:$(value).attr('value')});
        }
    });
    postData.bizEnumList = list;
    var url = basePath + 'bizOrgTeam/update';
    if(postData.id == ""){
        url=basePath + 'bizOrgTeam/insert';
        postData.orgCode = selectedOrgRow.orgCode;
        postData.isvPid = selectedOrgRow.isvPid;
    }else{
        postData.orgCode = selectedDataRow.orgCode;
        postData.teamCode = selectedDataRow.teamCode;
        postData.beforeList = beforeList;
        postData.afterList = afterList;
    }
    $.ajax({
        type: 'post',
        url:basePath + 'bizOrgTeam/getTeamRef',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success: function (data) {
            if (data.result) {
                 $.ajax({
                    type: 'post',
                    url:url,
                    dataType: 'json',
                    contentType: "application/json",
                    data: JSON.stringify(postData),
                    success: function (data) {
                        if (data.result) {
                            toastr.success(data.message);
                            $("#addPage").modal('hide');
                            doRefresh();
                        } else {
                            toastr.error(data.message);
                        }
                    },
                    error: function (request) {
                        toastr.error(common_system_error);
                    }});
            } else {
                swal({
                    title:"",
                    text:'该团队已和业务数据关联了,请谨慎修改?',
                    type:"warning",
                    showCancelButton:"true",
                    showConfirmButton:"true",
                    confirmButtonText:"确定",
                    cancelButtonText:"取消",
                    animation:"slide-from-top"
                }, function() {
                    $.ajax({
                        type: 'post',
                        url:url,
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(postData),
                        success: function (data) {
                            if (data.result) {
                                toastr.success(data.message);
                                $("#addPage").modal('hide');
                                doRefresh();
                            } else {
                                toastr.error(data.message);
                            }
                        },
                        error: function (request) {
                            toastr.error(common_system_error);
                        }});
                });
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }});


}

function change() {
    if (selectedDataRow =='') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    swal({
        title:"",
        text:'确认' +(selectedDataRow.status == 'available'?"冻结":"恢复")+'【'+selectedDataRow.teamName+'】吗'+'?',
        type:"warning",
        showCancelButton:"true",
        showConfirmButton:"true",
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        animation:"slide-from-top"
    }, function() {
        $.ajax({
            type: 'post',
            url: basePath + 'bizOrgTeam/changeStatus',
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify({id:selectedDataRow.id,status:selectedDataRow.status == 'available'?"disabled":"available"}),
            success: function (data) {
                if (data.result) {
                    toastr.success("机构团队"+(selectedDataRow.status == 'available'?"冻结":"恢复")+"成功");
                    doRefresh();
                } else {
                    toastr.error(data.message);
                }
            },
            error: function (request) {
                toastr.error(common_system_error);
            }
        });
    });
}

function del() {
    if (selectedDataRow =='') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.status == 'publish') {
        toastr.error('已发布的数据不能直接删除，请先撤销后再删除');
        return;
    }
    swal({
        title:"",
        text:'确认删除【'+selectedDataRow.teamName+'】吗'+'?',
        type:"warning",
        showCancelButton:"true",
        showConfirmButton:"true",
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        animation:"slide-from-top"
    }, function() {
        $.ajax({
            type: 'post',
            url: basePath + 'bizOrgTeam/delTeam',
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify({id:selectedDataRow.id,teamCode:selectedDataRow.teamCode,dataStatus:"delete"}),
            success: function (data) {
                if (data.result) {
                    toastr.success("机构团队删除成功");
                    doRefresh();
                } else {
                    toastr.error(data.message);
                }
            },
            error: function (request) {
                toastr.error(common_system_error);
            }
        });
    });
}



function selectRole() {
    $("#addNote").val("");
    resetFormTip("#note");
    resetInputCss("#note");
    $("#selectRole").modal(true);
}

function dosaveRole() {
    if(!$("#note").valid()) return;
    addNote('addNote','role',10);
    $("#selectRole").modal("hide");
}


//------------------------------------------------------------------------列表数据初始化
function formatStatus(value, row, index) {
    if(statusMap != null){
        return statusMap[value];
    }
    return "";
}
function formatDataStatus(value, row, index) {
    if(dataStatusMap != null){
        return dataStatusMap[value];
    }
    return "";
}

function initCheck(value, row, index) {
    if (isInitCheck && row.orgCode == searchInfo.orgCode) {
        setTimeout(function(){
            $("#orgTable > tbody > tr[data-index='" +index+"']").addClass("success");
        },200);
        isInitCheck = false;
        selectedOrgRow = row;
    }
    return value;
}

//----------------------------------------------------------------------提交發佈/撤銷發佈
function doOpenQrCode() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("提交发布"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error('待审核数据无法提交发布');
        return;
    }
    if (selectedDataRow.dataStatus == 'check_pass') {
        toastr.error('无修改的数据无需提交发布');
        return;
    }
    var postData = {
        teamCode : selectedDataRow.teamCode,
    };
    // $.ajax({
    //     type: 'post',
    //     url: basePath + 'bizOrgTeam/createQrCode?t=' + new Date().getTime(),
    //     dataType: 'json',
    //     contentType: "application/json",
    //     data: JSON.stringify(postData),
    //     success: function (data) {
    //         if(data.result){
    //             var content = data.content;
    //             console.log(content);
    //             $("#scanCode").attr("src",content.qrUrl);
    //             $("#_validNum").html(content.validNum);
    //             $("#scanQrCodePage").modal('show');
    //         }else{
    //             toastr.error(data.message);
    //         }
    //     },
    //     error: function (request) {
    //         toastr.error(common_system_error);
    //     }
    // });
    doShowQrCode( basePath + 'bizOrgTeam/createQrCode?t=' + new Date().getTime(),
        postData, 'minApp');
}


function refreshQrCode() {
    doShowQrCode( basePath + 'bizOrgTeam/createQrCode?t=' + new Date().getTime(),
        {
            teamCode : selectedDataRow.teamCode,
        }, 'minApp');
}



function closeScanOrCodePage() {
    $("#scanQrCodePage-common").modal('hide');
    $("#scanCodeMinApp").attr("src", '');
}

function doCommitTeam() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("提交发布"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error('待审核数据无法提交发布');
        return;
    }
    if (selectedDataRow.dataStatus == 'check_pass') {
        toastr.error('无修改的数据无需提交发布');
        return;
    }
    var postData = {
        id : selectedDataRow.id,
        teamCode : selectedDataRow.teamCode,
    };
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'bizOrgTeam/commitOrgTeam?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success: function (data) {
            hideLoading();
            if (!data) {
                toastr.error('提交失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            toastr.success('提交成功，等待管理员审核！');
            closeScanOrCodePage();
            doRefresh();
            return;
        },
        error: function (request) {
            hideLoading();
            toastr.error(common_system_error);
        }
    });
}

function doRevokeTeam() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("撤销"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error('待审核数据无法撤销发布');
        return;
    }
    if (selectedDataRow.status == 'unpublished') {
        toastr.error('此机构团队没有发布，不能撤销');
        return;
    }
    showSetReasonPage('revoke');
}

function showSetReasonPage(type) {
    s_operType = type;
    if (type == 'delete') {
        // $('#_modelTitle').html('删除');
        $('#_modelTip').html('删除');
    } else {
        // $('#_modelTitle').html('撤销发布');
        $('#_modelTip').html('撤销发布');
    }
    $('#setReasonPage').modal('show');
}

function doSaveReason() {
    if (s_operType == 'delete') {
        deleteOrg();
    } else if (s_operType == 'revoke') {
        doRevoke();
    } else {
        toastr.error(common_system_error);
    }
}

function doRevoke() {
    var reason = getReasonData();
    if (!reason || reason == '') {
        toastr.error('撤销原因不能为空');
        return;
    }
    var postData = {
        id : selectedDataRow.id,
        teamCode : selectedDataRow.teamCode,
        reason : reason
    };
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'bizOrgTeam/revokeOrgTeam?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success: function (data) {
            hideLoading();
            if (!data) {
                toastr.error('撤销失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            toastr.success('撤销发布成功');
            closeSetReasonPage();
            doRefresh();
            return;
        },
        error: function (request) {
            hideLoading();
            toastr.error(common_system_error);
        }
    });
}

function closeSetReasonPage() {
    $('#setReasonPage').modal('hide');
    $("input[type=checkbox][name=_reason]").removeAttr("checked");
    $('#reason').val('');
}

function getReasonData() {
    var checks=$('input[name="_reason"]:checked');
    var str = '';
    checks.each(function(idx,element){
        str += $(element).val() + ',';
    });
    var reason = $.trim($('#reason').val());
    str += reason;
    if (!reason || reason == '') {
        str = str.length > 0 ? str.substring(0, str.length - 1) : '';
    }
    return str;
}

function doExportExcel() {
    $('#searchForm').attr("action",basePath+"bizOrgTeam/exportTeamDataExcel?t=" + new Date().getTime());
    $('#searchForm').submit();
}
